package com.sky.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.service.IOrdersService;
import com.sky.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private IOrdersService iOrdersService;

    /**
     * 处理超时的方法
     */
    @Scheduled(cron = "0 * * * * *")
//    @Scheduled(cron = "1/5 * * * * ?")
    public void processTimeoutOrder(){
        log.info("定时处理超时订单：{}", LocalDateTime.now());
        LambdaQueryWrapper<Orders> lqw =new LambdaQueryWrapper<>();
        lqw.eq(Orders::getStatus,Orders.PENDING_PAYMENT);
        lqw.lt(Orders::getOrderTime,LocalDateTime.now().plusMinutes(-15));
        List<Orders> list = iOrdersService.list(lqw);
        if (list!=null&& !list.isEmpty()){
            for (Orders order : list) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                iOrdersService.updateById(order);
            }
        }
    }


    /**
     * 处理一直处于派送中的问题
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    //0秒 0分 1点 每天 每月 周（不指定）
    public void  processDeliveryOrder(){
        log.info("定时处理派送中订单：{}",LocalDateTime.now());
        LambdaQueryWrapper<Orders> lqw =new LambdaQueryWrapper<>();
//        lqw.eq(Orders::getUserId, ThreadLocalUtil.getValue());
        lqw.eq(Orders::getStatus,Orders.DELIVERY_IN_PROGRESS);
        lqw.lt(Orders::getOrderTime,LocalDateTime.now().plusMinutes(-60));
        //说明订单时间要在当天完成
        List<Orders> list = iOrdersService.list(lqw);
        if (list!=null&&!list.isEmpty()){
            for (Orders order : list) {
                order.setStatus(Orders.COMPLETED);
                iOrdersService.updateById(order);
            }
        }
    }
}
